

package com.dongdongshop.controller;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.dongdongshop.data.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@RequestMapping("file")
@Controller
@CrossOrigin
public class FileController {

    @RequestMapping("upLoad")
    @ResponseBody
    public Result upLoad(MultipartFile myFile){
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String https="https://";
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tFgh4wQN2GxBoy6wowN";
        String accessKeySecret = "diS7q4ckry99iFqQAGfO08hI9JOEaO";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "lfz-dongdongshop";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = "image/"+myFile.getOriginalFilename();

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(https+endpoint, accessKeyId, accessKeySecret);

        try {
            // 获取  流
            InputStream inputStream = myFile.getInputStream();

            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);

            ossClient.putObject(putObjectRequest);

            //url 下载路径
            String url = https+ bucketName +"."+endpoint+"/"+objectName;
            return Result.OK().setData(url);

        } catch (Exception e) {
            return Result.ER();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }


    }

}
